const { ErrorModel, SuccessModel } = require('./../utils/index')
const logger = require('./../utils/logger')
const { generatePageUrl } = require("../utils/index")
const { basePage, savePageFile } = require("./../config/index");
const { DataPageModel } = require('../models/page');
const { DataProjectModel } = require('../models/project');
const { writeFile, eventEmitter } = require('../utils/copyFile');
const fs = require("fs")
class PageController {
  /**
   * @description 添加页面
   * @param {*} project_id
   * @param {*} name
   * @param {*} thumb
   * @param {*} remark
   */
  static async pageAdd (req, res, next) {
    const { project_id, name, thumb, remark, layout } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`PageController`, `pageAdd`, `req.body`, req.body)
    if (!project_id || !name) {
      res.json(new ErrorModel([], `请输入专案名称或页面名称`))
      return
    }
    try {
      const pageInfo = await DataPageModel.findByNameAndProjectId(name, project_id)
      if (pageInfo) {
        res.json(new ErrorModel([], `当前项目下此页面已存在`))
        return
      }
      const result = await DataPageModel.create(name, project_id, thumb, remark, op_user_id, layout)
      logger.info(`PageController`, `pageAdd`, `result`, result)
      if (result.page_id) {
        let page_url = generatePageUrl(result.project_id, result.page_id)
        const updatePageUrl = await DataPageModel.updatePageURL(result.page_id, page_url)
        const url = `${savePageFile}${page_url}.json`
        const pageInfo = JSON.stringify(basePage)
        eventEmitter.emit("writeFile", url, pageInfo)
        logger.info(`PageController`, `pageAdd`, `result`, updatePageUrl)
      }
      res.json(new SuccessModel([], `新增页面成功`))
    } catch (error) {
      logger.error(`PageController`, `pageAdd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 更新页面
   * @param {*} page_id
   * @param {*} project_id
   * @param {*} name
   * @param {*} thumb
   * @param {*} remark
   */
  static async pageUpd (req, res, next) {
    const { page_id, name, thumb, remark, publish, project_id, layout } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`PageController`, `pageUpd`, `req.body`, req.body)
    if (!page_id || !project_id) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const pageInfo = await DataPageModel.findByNameAndProjectIdNePageId(name, project_id, page_id)
      if (pageInfo) {
        res.json(new ErrorModel([], `当前项目下此页面已存在`))
        return
      }
      const result = await DataPageModel.update(name, thumb, remark, publish, op_user_id, page_id, layout)
      logger.info(`PageController`, `pageUpd`, `result`, result)
      res.json(new SuccessModel([], `页面更新成功`))
    } catch (error) {
      logger.error(`PageController`, `pageUpd`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 删除页面
   * @param {*} page_id
   */
  static async pageDel (req, res, next) {
    const { page_id } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`PageController`, `pageDel`, `req.body`, req.body)
    if (!page_id) {
      res.json(new ErrorModel([], `page_id 获取失败`))
      return
    }
    try {
      const result = await DataPageModel.delete(op_user_id, page_id)
      logger.info(`PageController`, `pageDel`, `result`, result)
      res.json(new SuccessModel([], `删除页面成功`))
    } catch (error) {
      logger.error(`PageController`, `pageDel`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * @description 页面分页列表
   * @param {*} page_id
   */
  static async pageList (req, res, next) {
    const { limit, size = 1, name, remark, project_id } = req.query
    logger.info(`PageController`, `pageList`, `req.query`, req.query)
    if (!project_id) {
      res.json(new ErrorModel([], `缺少project_id字段`))
      return
    }
    try {
      const { result, count } = await DataPageModel.list(limit, size, name, remark, project_id,)
      logger.info(`PageController`, `pageList`, `result`, result, count)
      res.json(new SuccessModel({ result, total: count[0].count, limit: Number(limit), size: Number(size) }, `获取页面数据成功`))
    } catch (error) {
      logger.error(`PageController`, `pageList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 页面分页列表
   * @param {*} page_id
   */
  static async pageInfoById (req, res, next) {
    const { page_id } = req.query
    logger.info(`PageController`, `pageInfoById`, `req.query`, req.query)
    if (!page_id) {
      res.json(new ErrorModel([], `缺少page_id字段`))
      return
    }
    try {
      const pageInfo = await DataPageModel.findByPageId(page_id)
      logger.info(`PageController`, `pageInfoById`, `result`, pageInfo)
      res.json(new SuccessModel({ result: pageInfo }, `获取页面数据成功`))
    } catch (error) {
      logger.error(`PageController`, `pageInfoById`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 获取project信息和page信息
   * 
   */
  static async listByProjectId (req, res, next) {
    const { name, remark, project_id,size,limit } = req.query
    logger.info(`PageController`, `pageList`, `req.query`, req.query)
    if (!project_id) {
      res.json(new ErrorModel([], `缺少project_id字段`))
      return
    }
    try {
      console.log(Number(size),size,"Number(size),size");
      const { result, count } = await DataPageModel.listByProjectId(Number(size),Number(limit),name, remark, project_id,)
      logger.info(`PageController`, `pageList`, `result`, result, count)
      const projectInfo = await DataProjectModel.findByProjectId(project_id)
      // res.json(new SuccessModel({ pageList: result, projectInfo, total: count[0].count, }, ``))
      res.json(new SuccessModel({ result, total: count[0].count, projectInfo,limit: Number(limit), size: Number(size) }, `获取页面数据成功`))

    } catch (error) {
      logger.error(`PageController`, `pageList`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
  * @description 发布页面
  * @param {*} page_id
  * @param {*} publish
  */
  static async pagePublish (req, res, next) {
    const { page_id } = req.body
    const { user_id: op_user_id } = req.user
    logger.info(`PageController`, `pagePublish`, `req.body`, req.body)
    if (!page_id) {
      res.json(new ErrorModel([], `请输入必填项`))
      return
    }
    try {
      const result = await DataPageModel.publish(op_user_id, page_id)
      logger.info(`PageController`, `pagePublish`, `result`, result)
      res.json(new SuccessModel([], `页面发布成功`))
    } catch (error) {
      logger.error(`PageController`, `pagePublish`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * @description 发布页面
   * @param {*} page_id
   * @param {*} json
   */
  static async savePageInfo (req, res, next) {
    const { page_url, json } = req.body
    if (!page_url || !json) {
      res.json(new ErrorModel([], `缺少必要参数`))
      return;
    }
    writeFile(savePageFile, `${page_url}.json`, json).then((res) => {
      res.json(new SuccessModel([{ file: res }], "写入成功"))
    }).catch(err => {
      res.json(new ErrorModel([], err.message))
    })
  }
  /**
   * @description 读取页面
   * @param {*} page_id
   */
  static async readPageInfo (req, res, next) {
    const { page_url } = req.body
    if (!page_url) {
      res.json(new ErrorModel([], `缺少必要参数`))
      return;
    }
    logger.info(`PageController`, `readPageInfo`, `req.body`, page_url)
    const data = fs.readFileSync(`${savePageFile}${page_url}.json`, 'utf-8')
    res.json(new SuccessModel({ result: data }, "读取成功"))
  }
  /**
  * @description 拷贝页面
  * @param {*} page_id
  */
  static async pageCopyById (req, res, next) {
    const { page_id } = req.query
    const { user_id: op_user_id } = req.user
    logger.info(`PageController`, `pageCopyById`, `req.query`, req.query)
    if (!page_id) {
      res.json(new ErrorModel([], `缺少page_id字段`))
      return
    }
    try {
      const pageInfo = await DataPageModel.findByPageId(page_id)
      logger.info(`PageController`, `pageCopyById`, `result`, pageInfo)
      const { project_id, name, thumb, remark, } = pageInfo
      const result = await DataPageModel.create(name, project_id, thumb, remark, op_user_id,)
      logger.info(`PageController`, `pageCopyById`, `result`, result)
      if (result.page_id) {
        let page_url = generatePageUrl(result.project_id, result.page_id)
        const updatePageUrl = await DataPageModel.updatePageURL(result.page_id, page_url)
        logger.info(`PageController`, `pageCopyById`, `result`, updatePageUrl)
        const fromFileName = `${savePageFile}${pageInfo.page_url}.json`
        const toFileName = `${savePageFile}${page_url}.json`
        eventEmitter.emit("copyFile", fromFileName, toFileName)
        res.json(new SuccessModel(result, `页面拷贝成功`))
      }
    } catch (error) {
      logger.error(`PageController`, `pageCopyById`, `error`, error)
      res.json(new ErrorModel([], error.message))
    }
  }
}

module.exports = {
  PageController,
}
